package com.test.reggie.model.jiesuan;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.test.reggie.R;
import com.test.reggie.base.BaseActivity;
import com.test.reggie.base.BaseRVAdapter;
import com.test.reggie.base.BaseRVHolder;
import com.test.reggie.bean.AddAddressBean;
import com.test.reggie.bean.AddressBookListBean;
import com.test.reggie.bean.ShoppingCartListBean;
import com.test.reggie.bean.State;
import com.test.reggie.bean.StringBean;
import com.test.reggie.bean.UserBean;
import com.test.reggie.databinding.ActivityJiesuanBinding;
import com.test.reggie.http.API;
import com.test.reggie.model.address.AddressActivity;
import com.yechaoa.yutils.GsonUtil;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 去结算（订单详情）
 */
public class JiesuanActivity extends BaseActivity<ActivityJiesuanBinding, JiesuanPresenter> implements
        JiesuanView, View.OnClickListener {

    private UserBean userBean;
    private int CHOOSE_ADDRESS = 201;
    private BaseRVAdapter<ShoppingCartListBean.DataBean> carAdapter;
    private String addressBookId;

    @Override
    protected JiesuanPresenter createPresenter() {
        return new JiesuanPresenter(this);
    }

    @Override
    protected void initView() {
        viewBinding.ic.tvTitle.setText("订单结算");
        viewBinding.ic.llBack.setOnClickListener(this);
        viewBinding.llChooseAddress.setOnClickListener(this);
        viewBinding.btnZhifu.setOnClickListener(this);

        userBean = GsonUtil.GsonToBean(String.valueOf(API.kv.decodeString(State.user)),
                UserBean.class);
        if (userBean.getData() != null && userBean.getData().getId() != null) {
            presenter.getDefault(userBean.getData().getId());//查询默认地址

            YUtils.showLoading("加载中...");
            presenter.shoppingCartList(userBean.getData().getId());//查看购物车
        }
    }

    @Override
    protected void initData() {
        carAdapter = new BaseRVAdapter<ShoppingCartListBean.DataBean>(R.layout.item_jiesuan) {
            @Override
            public void onBindVH(BaseRVHolder holder, ShoppingCartListBean.DataBean data, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                TextView tv_num = holder.getView(R.id.tv_num);
                CircleImageView civ = holder.getView(R.id.civ);

                Glide.with(JiesuanActivity.this).load(API.kv.decodeString(State.ip) +
                        "/common/download?name=" + data.getImage())
                        .placeholder(R.drawable.icon_no_data).into(civ);

                tv_name.setText("" + data.getName());
                tv_num.setText("x" + data.getNumber());

                holder.setText(R.id.tv_price, "￥" + data.getAmount());
            }
        };
        viewBinding.rvOrder.setAdapter(carAdapter);
        viewBinding.rvOrder.setLayoutManager(new GridLayoutManager(JiesuanActivity.this, 1));//列数设置
    }

    @Override
    public void getDefaultSuccess(AddAddressBean bean) {
        if (bean.getCode() == 200) {
            viewBinding.tvAddress.setText(bean.getData().getDetail());//详细地址
            viewBinding.tvName.setText(bean.getData().getConsignee());//姓名
            viewBinding.tvPhone.setText(bean.getData().getPhone());//手机号
            addressBookId = bean.getData().getId();
        } else {
            viewBinding.tvAddress.setHint("请选择地址");//详细地址
        }
    }

    @Override
    public void onError(String msg) {
        YUtils.hideLoading();
        ToastUtil.showCenter(msg);
    }

    @Override
    public void shoppingCartListSuccess(ShoppingCartListBean bean) {
        YUtils.hideLoading();
        if (bean.getCode() == 200) {
            carAdapter.setNewData(bean.getData());

            BigDecimal zongjia = new BigDecimal(0);
            BigDecimal znum = new BigDecimal(0);
            for (int i = 0; i < bean.getData().size(); i++) {
                BigDecimal num = new BigDecimal(bean.getData().get(i).getNumber());
                BigDecimal amount = bean.getData().get(i).getAmount();
                BigDecimal jiage = num.multiply(amount);
                zongjia = zongjia.add(jiage);
                znum = znum.add(num);
            }
            viewBinding.tvZongjia.setText("￥" + zongjia);

            if (Integer.parseInt(String.valueOf(znum)) > 99) {
                viewBinding.tvNum.setText("99+");
            } else {
                viewBinding.tvNum.setText("" + znum);
            }
        } else {
            ToastUtil.showCenter(bean.getMsg());
        }
    }

    @Override
    public void submitOrdersSuccess(StringBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            setResult(Activity.RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHOOSE_ADDRESS && resultCode == Activity.RESULT_OK) {
            AddressBookListBean.DataBean dataBean = data.getParcelableExtra("data");
            viewBinding.tvAddress.setText(dataBean.getDetail());//详细地址
            viewBinding.tvName.setText(dataBean.getConsignee());//姓名
            viewBinding.tvPhone.setText(dataBean.getPhone());//手机号
            addressBookId = dataBean.getId();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_zhifu://去支付
                if (TextUtils.isEmpty(viewBinding.tvAddress.getText().toString())) {
                    ToastUtil.showCenter("请选择地址");
                } else {
                    YUtils.showLoading("提交中...");
                    Map<String, Object> mapSubmitOrders = new HashMap<>();
                    mapSubmitOrders.put("userId", userBean.getData().getId());//用户id
                    mapSubmitOrders.put("addressBookId", addressBookId);//地址id
                    mapSubmitOrders.put("payMethod", 1);//支付方式
                    mapSubmitOrders.put("remark", viewBinding.etRemark.getText().toString().trim());//备注
                    presenter.submitOrders(mapSubmitOrders);//用户下单
                }
                break;
            case R.id.ll_choose_address://选择地址
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("type", "jiesuan");
                startActivityForResult(intent, CHOOSE_ADDRESS);
                break;
            case R.id.ll_back:
                finish();
                break;
            default:
                break;
        }
    }
}